package hello;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * Created by Germmy on 2017/11/4.
 */
public class MyClient implements  Runnable {

    public static int num=0;

    public static void main(String[] args) {
        try {
            //创建zookeeper的客户端
            RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
            CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.92.135:2181", retryPolicy);
            client.start();

            //创建分布式锁, 锁空间的根节点路径为/curator/lock
            InterProcessMutex mutex = new InterProcessMutex(client, "/curator/lock");
            mutex.acquire();
            //获得了锁, 进行业务流程
            System.out.println("Enter mutex");
            //完成业务流程, 释放锁
            mutex.release();

            //关闭客户端
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    public void run(){
        System.out.println("进入了MyClient1...");
        try {
            System.out.println("进入了MyClient2...");
            //创建zookeeper的客户端
            RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
            CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.92.135:2181", retryPolicy);
            client.start();

            //创建分布式锁, 锁空间的根节点路径为/curator/lock
            InterProcessMutex mutex = new InterProcessMutex(client, "/curator/lock");
            mutex.acquire();
            //获得了锁, 进行业务流程
            num++;
            System.out.println("当前线程ID是："+Thread.currentThread().getId()+",数字是:"+num);
            //完成业务流程, 释放锁
            mutex.release();

            //关闭客户端
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



}
